package com.lkskt.frame.jni;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zdj.data.base.BaseDatas;
import com.zdj.data.entity.LoginInfo;
import com.zdj.data.events.LoginEvent;
import com.zdj.data.utils.JsonUtils;
import com.zdj.utils.MyLogUtil;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;

//SS_LOGIN = 1   //登录
//SS_EXIT = 2    //退出登录
//SS_MSG = 10    //发送消息
//SS_GETOFFMSG = 11//获取离线消息
//SS_ANDROID_INIT = 30//初始化服务器地址
//SS_ANDROID_TIMEOUT = 31//请求超时


public class Liblksjni {

    private static final String TAG = "Liblksjni";

    public static final int SS_LOGIN = 1;
    public static final int SS_EXIT = 2;
    public static final int SS_KEEPALIVE = 3;
    public static final int SS_RELOGIN = 4;


    public static final int SS_MSG = 10;
    public static final int SS_GETOFFMSG = 11;
    public static final int SS_ANDROID_INIT = 30;
    public static final int SS_ANDROID_TIMEOUT = 31;
    public static final int LOGIN_TIMEOUT = 3000;
    public static final int GETOFFMSG_TIMEOUT = 3001;
    public static final int ACK_TIMEOUT = 3002;
    public static final int KEEPALIVE_TIMEOUT = 3003;



    public static final int EC_OTHER_LOGIN = 1;
    public static final int EC_OTHER_LOGIN_CODE = 100001;
    public static final int EC_PW_CHANGE = 2;
    public static final int EC_PW_CHANGE_CODE = 200001;
    public static final int EC_ACCOUNT_DISABLE = 3;
    public static final int EC_ACCOUNT_DISABLE_CODE = 300001;
    public static final int EC_TIMEOUT = 4;
    public static final int EC_TIMEOUT_CODE = 400001;
    // EC_OTHER_LOGIN = 1 // 异地登录（跳到登录页面,让用户手动登录)
    // EC_PW_CHANGE = 2 // 密码更改
    // EC_ACCOUNT_DISABLE = 3 // 帐号被禁用
    // EC_TIMEOUT = 4 // 登录已超时（自动重登录）


    private static Handler handler;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    private static Liblksjni mLiblksjni;

    public static Liblksjni getInstance() {
        if (mLiblksjni == null) {
            mLiblksjni = new Liblksjni();
        }

        return mLiblksjni;
    }

    static {
        System.loadLibrary("lksjni");
    }


    public native int lksudprequest(int cmd, String val);

    public native int lksudprequestex(int cmd, byte[] buf);


    public Liblksjni() {
        Log.d("lkslog", "[开始]");
    }

    public static void lksudpcallbackbyte(byte[] buf) {
//		String strBuf = ByteUtil.getString(buf);
//		Log.e("lkslog-byte", "buflen=" + buf.length + ",buf=" + strBuf);
    }

    public static void lksudpcallback(int cmd, String strParam) {
        MyLogUtil.d(TAG, "lksudpcallback: \n" + strParam);
        Message message = handler.obtainMessage();
        switch (cmd) {
            case SS_LOGIN: // 登录成功，返回登录信息
                BaseDatas<LoginInfo> loginInfoBaseDatas =
                        JsonUtils.deserialize(strParam,new TypeToken<BaseDatas<LoginInfo>>() {}.getType());
                EventBus.getDefault().post(new LoginEvent(loginInfoBaseDatas.data));
                break;
            case SS_EXIT:
                // 通知下线：异地登录等通知"exit_type" -> EXIT_CMD
                // EC_OTHER_LOGIN = 1 // 异地登录（跳到登录页面,让用户手动登录)
                // EC_PW_CHANGE = 2 // 密码更改
                // EC_ACCOUNT_DISABLE = 3 // 帐号被禁用
                // EC_TIMEOUT = 4 // 登录已超时（自动重登录）
                ExitResponse exitResponse = JsonUtils.deserialize(strParam,ExitResponse.class);
                switch (exitResponse.exit_type){
                    case EC_ACCOUNT_DISABLE:
                        handler.obtainMessage(EC_ACCOUNT_DISABLE_CODE).sendToTarget();
                        break;
                    case EC_OTHER_LOGIN:
                        handler.obtainMessage(EC_OTHER_LOGIN_CODE).sendToTarget();
                        break;
                    case EC_PW_CHANGE:
                        handler.obtainMessage(EC_PW_CHANGE_CODE).sendToTarget();
                        break;
                    case EC_TIMEOUT:
                        handler.obtainMessage(EC_TIMEOUT).sendToTarget();
                        break;
                }
                break;
            case SS_MSG: // 收到消息
                message.what = SS_MSG;
                message.obj = strParam;
                handler.sendMessage(message);
                break;
            case SS_GETOFFMSG:
                message.what = SS_GETOFFMSG;
                message.obj = strParam;
                handler.sendMessage(message);
                break;
            case SS_ANDROID_INIT:
                MyLogUtil.d(TAG, "SS_ANDROID_INIT: \n" + strParam);
                break;
            case SS_ANDROID_TIMEOUT: // 请求超时，ackid为请求时返回的id cmd 为请求的类型   {"ackid"=32313333 "cmd"=1}
                MyLogUtil.d(TAG, "SS_ANDROID_TIMEOUT: \n" + strParam);
                // 根据cmd判断，发送何种消息，登录超时 或者 掉线 或者 接收离线消息
                TimeOutResponse timeOutResponse = JsonUtils.deserialize(strParam,TimeOutResponse.class);
                if(timeOutResponse.cmd == SS_LOGIN){ // 登录超时
                    message.what = LOGIN_TIMEOUT;
                }else if(timeOutResponse.cmd == SS_GETOFFMSG){ // 接收离线消息超时
                    message.what = GETOFFMSG_TIMEOUT;
                }else if(timeOutResponse.cmd == SS_KEEPALIVE){// udp断开 心跳超时
                    message.what = KEEPALIVE_TIMEOUT;
                }else{
                    message.what = ACK_TIMEOUT;
                }
                handler.sendMessage(message);
                break;
        }
    }

    private class ExitResponse{
        public int cmd;
        public int exit_type;
    }

    private class TimeOutResponse{
        public int ackid;
        public int cmd;

        public TimeOutResponse(int ackid, int cmd) {
            this.ackid = ackid;
            this.cmd = cmd;
        }
    }

    public static final String PATH = Environment.getExternalStorageDirectory().toString();

    public String GetShowStr() {
        String strShow;
        int ackid = 0;

        strShow = "\n\n初始化：服务器IP,端口,\n";
        ackid = lksudprequest(30, "112.124.118.60,7777,");
        strShow += "返回ackid=" + ackid + "\n";

        strShow = "\n\n登录：帐号,密码MD5,uuid,\n";
        ackid = lksudprequest(1, "18096634454,e10adc3949ba59abbe56e057f20f883e,1024,");
        strShow += "返回ackid=" + ackid + "\n";

        strShow = "\n\n获取离线消息：msgid,\n";
        ackid = lksudprequest(11, "1024,");
        strShow += "返回ackid=" + ackid + "\n";

        strShow = "\n\n退出登录：\n";
        ackid = lksudprequest(2, "");
        strShow += "返回ackid=" + ackid + "\n";

        return strShow;
    }

}
